<template>
  <div class="upload_orc">
    <div class="upload_orc_title">
      <el-button type="primary" @click="loadFile">
       上传文件<el-icon class="el-icon--right"><Upload /></el-icon>
      </el-button>
       <p>识别文件区域请上传{{ocrType == 'Api' ? 'PDF、PNG、JPG' : 'PDF、PNG、JPG '}}等格式文件(最大为10MB)</p>
    </div>
    <div class="upload_orc_result">
      <a-empty v-if='!onlineSrc'>
        <template #image>
          <icon-exclamation-circle-fill />
        </template>
        请上传文件
      </a-empty>
       <!-- 文档预览的位置 -->
       <iframe v-else :src="onlineSrc" scrolling="auto" frameborder="0" class="iframeClass"></iframe>
    </div>
  </div>
</template>
     
<script setup lang='ts'>
import { Message } from "@arco-design/web-vue"
import { IconExclamationCircleFill } from '@arco-design/web-vue/es/icon';
import {  Upload } from '@element-plus/icons-vue'
import { make } from '@/components/EditorJs/utils/dom';
import { apiOcrGetOcr,apiOcrGetUpload,apiOcrGetUploadStatus } from '@/api/ocrApi';
import onlinePreviewApi from '@/api/onlinePreview/onlinePreviewApi'
const emit = defineEmits(['uploadSuccess'])
import axios from 'axios';
import {resource} from '@/api/apiModulesType';
import { getToken } from '@/utils/auth';
const instance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 500000,
  headers: {
    'Authorization':'Bearer ' + getToken(),
    'Content-Type':'multipart/form-data'
  }
});
let ocrType = ref('')
// 获取ocr识别类型 系统内置OCR：MinerU   第三方API（合合）：Api
const getOrcType = async () =>{
    const res = await apiOcrGetOcr();
    ocrType.value = res.msg
}
const isUpload = ref<Boolean>(true)
// 上传文件
const loadFile = () => {
  if(!isUpload.value){
    Message.error('正在识别中，请勿重复上传');
    return;
  }
  const fileDom = make('input', '', { type: 'file', accept: ocrType.value == 'Api' ? '.pdf,.png,.jpg' : '.pdf,.png,.jpg'  });
  fileDom.style.display = 'none';
  document.body.append(fileDom);
  fileDom.click();
  fileDom.addEventListener("change", async (event: any) => {
    const file = event.target.files[0];
    let size = file.size / (1024 * 1024)
    if(size > 10){
      Message.error('上传文件大于10MB，请重新上传！');
      return;
    }
    let fromData = new FormData();
    fromData.append('file', file);
    
    isUpload.value = false;
    const loading = ElLoading.service({
      lock: true,
      text: 'OCR识别中...',
      background: 'rgba(0, 0, 0, 0.1)',
    })
    instance.post(`/${resource}/ocr/upload`, fromData)
      .then(function (res:any) {
          emit('uploadSuccess', res.data.data.ocrResult, res.data.data.storageId)
          getFileDataInfo(res.data.data.storageId)
          isUpload.value = true;
          Message.success('识别成功'); 
          loading.close()
        })
      .catch(function (error) {
          console.log(error);
          loading.close()
        });
    // if(ocrType.value == 'Api'){
      // const res:any = await apiOcrGetUpload(fromData);
      // emit('uploadSuccess', res.data.ocrResult)
      // getFileDataInfo(res.data.storageId)
      // isUpload.value = true;
      // Message.success('识别成功'); 
      // loading.close()
    // }
    // if(ocrType.value == 'MinerU'){
    //   const res:any = await apiOcrGetUpload(fromData);
    //   getFileDataInfo(res.data.storageId)
    //   let intervalId = setInterval(async () => {
    //    let res1:any = await apiOcrGetUploadStatus({id:res.data.id});
    //    if(res1.data.status == 'done'){
    //      clearInterval(intervalId);
    //      Message.success('识别成功');
    //      emit('uploadSuccess', res1.data.ocrResult)
    //      isUpload.value = true;
    //      loading.close()
    //    }
    //    if(res1.data.status == 'failed'){
    //     Message.error('识别失败 请重新上传');
    //     clearInterval(intervalId);
    //     isUpload.value = true;
    //     loading.close()
    //    }
    //   }, 5000)
    // }
    // 上传文件逻辑
  });
};
const onlineSrc = ref('')
const getFileDataInfo = (id:string) => {
  let params = {
    moduleId: id,//文件id
    versionId: null,//文件版本
    type: 'temporary',//类型 不同模块库编码
  }
  onlinePreviewApi.getFileDataInfo(params).then((res: any) => {
    // onlineSrc.value = 'http://' + res.data.url
    onlineSrc.value =  res.data.url;
  })
}
onMounted(()=>{
    getOrcType();
})
</script>
<style scoped lang='scss'>
.upload_orc{
  width: 50%;
  border-right: 1px solid #ccc;
  .upload_orc_title{
    background-color: white;
    height: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
    p{
      margin-left: 20px;
      font-size: 14px;
      color: #666;
    }
  }
  .upload_orc_result{
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
.iframeClass {
  width: 80%;
  height: 90%;
  border-radius: 10px;
}
</style>